package com.example.demo.config;

import com.example.demo.service.SysUserService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.util.HashMap;
import java.util.Map;

@Configuration
//@EnableWebSecurity//指定为Spring Security配置类
//@EnableGlobalMethodSecurity(prePostEnabled = true) // 启用方法安全设置
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private SysUserService sysUserService;

    @Bean
    PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 配置可以访问本项目的用户名密码和角色
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        /*auth.inMemoryAuthentication()
                .withUser("admin").password("$2a$10$3aE97fMlIWtlMuH7Cbbb9uxaSo49VFXnZSL9wdE62D1uej/TaPViq").roles("ADMIN")
                .and()
                .withUser("sang").password("$2a$10$V92r7Jneg/j1y0IiF.gd0eEc3D3xDskKlMEQpc3jrgchm0iq7lk9.").roles("USER");*/
        auth.userDetailsService(sysUserService);
    }

    /**
     * 配置访问项目中的资源（接口/控制器/功能）需要的角色
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
//                .antMatchers(HttpMethod.GET,"/articles/**").hasAnyRole("admin","user")
//                .antMatchers(HttpMethod.PUT,"/articles/{id}").hasRole("admin")
//                .antMatchers(HttpMethod.POST,"/articles").hasRole("admin")
//                .antMatchers(HttpMethod.DELETE,"/articles/{id}").hasRole("admin")
                .antMatchers("/articles/**","/users/**")
                .access("@rbacService.hasPermission(request, authentication)")
                .anyRequest().authenticated()//除上面配置的以外的资源必须登录以后才能访问
                .and()
                .formLogin()
                .loginPage("/login-page")
                .loginProcessingUrl("/mylogin")
//                .successForwardUrl("/home.htm")
                .successHandler((httpServletRequest, response, authentication) -> {
                    response.sendRedirect("/home.htm");
                })
                .permitAll()//所有人都可以访问
                .and()
                .logout()
                .and().csrf().disable();

    }

    /**
     * 不用保护的静态资源
     * @param web
     * @throws Exception
     */
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring()
//                .antMatchers("/**/*.htm")
                .antMatchers("/**/*.js")
                .antMatchers("/v2/api-docs", "/swagger-resources/configuration/ui",
                        "/swagger-resources", "/swagger-resources/configuration/security",
                        "/swagger-ui.html", "/webjars/**");

    }

    public static void main(String[] args) {
        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        System.out.println(passwordEncoder.encode("123456"));
        System.out.println(passwordEncoder.encode("123456"));
        System.out.println(passwordEncoder.encode("123456"));
    }
}
